﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using ClientCommonWpf;
using Director.DomainModels;

namespace Director.ViewModels
{
	class PositionsVM : AbstractToolVM
	{
		private Dictionary<Security, decimal> _pnls;

		public PositionsVM(MainVM mainVM) : base(mainVM)
		{
			TotalPnL = 0m;
		}

		public override string Title
		{
			get { return "Позиции"; }
		}

		public override void Init()
		{
			ListenTimeFrame = DataManager.Instance[TimeFrame.ELength.M1];
			MainVM.GetLastCandles(DataManager.Instance.SharesByCodes, ListenTimeFrame);

			Task.Factory.StartNew(() =>
			{
				_pnls = DataManager.Instance.SharesByCodes.ToDictionary(s => s, s => DataManager.Instance.DirectorStorage.CalculatePnL(s));
			
				//foreach (var security in DataManager.Instance.SharesByCodes)
				//{
				//	TotalPnL += DataManager.Instance.DirectorStorage.CalculatePnL(security);
				//}

				DataManager.Instance.DirectorStorage.ReadAllOrders();

				TotalPnL = _pnls.Sum(e => e.Value);

				Debug.WriteLine("TOTAL PNL : " + TotalPnL.ToString("N"));

				Update();
			});
		}

		public override EToolId ToolId
		{
			get { return EToolId.POSITIONS; }
		}

		public override void CandlesUpdated()
		{
			foreach (var security in ListenSecurities)
			{
				MainVM.GetCandles(security, ListenTimeFrame);
			}
		}

		public void Update()
		{
			Items = DataManager.Instance.Positions.Select(e => new PositionVM(e)).OrderBy(e => e.Name).ToList();
			foreach (var security in _pnls.Where(p=>p.Value!=0).Select(e=>e.Key))
			{
				if (Items.Any(e => e.Position.SecId == security.Id))
				{
					continue;
				}
				Items.Add(new PositionVM(new Position(){Name = security.Name, SecId = security.Id,Saldo = 0}));
			}
			var money = Items.Single(e => e.Position.SecId == 0);

			money.Summ = 0;
			money.UnrealizedPnL = 0;
			money.PnL = 0;

			foreach (var vm in Items)
			{
				if (vm != money) //если не деньги
				{
					var security = DataManager.Instance.Securities[vm.Position.SecId];
					vm.AveragePrice = DataManager.Instance.DirectorStorage.GetAveragePrice(security.Code);
					vm.CurrentPrice = MainVM.GetCurrentPrice(security);
					vm.StopLoss = DataManager.Instance.DirectorStorage.ReadStopLoss(security);
					vm.UnrealizedPnL = (vm.CurrentPrice - vm.AveragePrice) * vm.Position.Saldo * security.Lotsize;
					vm.Summ = vm.CurrentPrice*vm.Position.Saldo*security.Lotsize;
					vm.PnL = _pnls[security];

					money.Summ += vm.Summ;
					money.UnrealizedPnL += vm.UnrealizedPnL;
					money.PnL += vm.PnL;

					StartListenCandles(security);
				}
			}

			MainVM.UpdateTitleInfo(money.UnrealizedPnL);

			OnPropertyChanged(()=>Items);
		}

		public List<PositionVM> Items { get;private set; }

		public decimal TotalPnL { get; private set; }
	}

	class PositionVM : AbstractNotifier
	{
		public PositionVM(Position position)
		{
			Position = position;
			Name = position.SecId==0?"-":position.Name;
		}

		public string Name { get; set; }

		public Position Position { get; set; }

		/// <summary>
		/// текущая цена актива
		/// </summary>
		public decimal? CurrentPrice { get; set; }

		/// <summary>
		/// средняя цена имеющихся бумаг
		/// </summary>
		public decimal? AveragePrice { get; set; }

		public decimal? StopLoss { get; set; }

		public decimal? UnrealizedPnL { get; set; }

		public decimal? PnL { get; set; }

		public decimal? Summ { get; set; }
	}
}
